#pragma once
#include <iostream>
#include <string>
#include <strings.h>
#include <cstdlib>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define NUM 1024
class TcpClient
{
public:
    TcpClient(const std::string &ip, const uint16_t &port)
    :_serverip(ip), _serverport(port), _sockfd(-1)
    {}
    void initClient()
    {
        //创建套接字对象
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd == -1)
        {
            std::cerr << "socket error" << std::endl;
            exit(2);
        }
        std::cout << "socket success" << std::endl;

        //不需要手动绑定ip和端口
    }
    void start()
    {
        //与服务器建立连接
        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());
        server.sin_port = htons(_serverport);
        int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
        if(n == -1)
        {
            std::cerr << "connect error" << std::endl;
            exit(3);
        }
        std::cout << "connect server success" << std::endl;
        std::string message;
        char buffer[NUM];
        while(1)
        {
            //发送信息
            std::cout << "Enter@ ";
            std::getline(std::cin, message);
            ssize_t n = write(_sockfd, message.c_str(), message.size());
            if(n == -1)
            {
                std::cerr << "write error" << std::endl;
                continue;
            }

            n = read(_sockfd, buffer, sizeof(buffer) - 1);
            if(n >= 0)
            {
                buffer[n] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                break;
            }
        }
    }
    ~TcpClient()
    {
        if(_sockfd >= 0) close(_sockfd);
    }
private:
    std::string _serverip;
    uint16_t _serverport;
    int _sockfd; 
};
